package concole;

import java.io.BufferedReader;
import java.io.FileReader;

public class UserLoginEnter {
	User user;
	int idInt;
	String[] inputInfo;

	public UserLoginEnter() {

	}

	public UserLoginEnter(int idInt, String[] inputInfo) {
		this.idInt = idInt;
		this.inputInfo = inputInfo;
	}

	public UserLoginEnter(User user) {
		this.user = user;
	}

	public void go() {
		if (!((inputInfo[1].equals("student") && idInt == 3) || (inputInfo[1]
				.equals("teacher") && idInt == 2))) {
			System.out.println("sorry idetity not matches");
			return;
		}

		if (inputInfo.length == 4) {
			 if (inputInfo[2].isEmpty()||inputInfo[3].isEmpty()){
					System.out.println("sorry the message is in need ");
				}
			if (!((inputInfo[1].equals("student")) || (inputInfo[1]
					.equals("teacher")))) {
				System.out.println("ideneity not allowed");
			}
			if (this.checkCompitable(inputInfo[2].substring(1, inputInfo[2]
					.indexOf("]")), inputInfo[3].substring(1, inputInfo[3]
					.indexOf("]")), idInt)) {
				switch (idInt) {
				case 2:
					user = new Teacher(inputInfo[2].substring(1, inputInfo[2]
							.indexOf("]")));
					user.startOperation();
					break;
				case 3:
					user = new Student(inputInfo[2].substring(1, inputInfo[2]
							.indexOf("]")));
					user.startOperation();
					break;
				}
			}
		} else {
			System.out.println("sorry format error");
		}
	}

	public boolean checkCompitable(String userID, String passwordIn, int idInt) {
		boolean IDright = false;
		boolean passRight = false;
		try {
			String fileName = "studentAccounts.txt";
			if (idInt == 2) {
				fileName = "teacherAccounts.txt";
			}
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String newAccountRecord = null;
			while ((newAccountRecord = bufferedReader.readLine()) != null) {
				String[] newInfo = newAccountRecord.split(" ");
				// get the ID and password from the file;
				if (newInfo[0].equals(userID)) {

					IDright = true;
					if (newInfo[1].equals(passwordIn)) {
						System.out.println("You have successfully logined.");
						return true;
					}
				}
			}
		} catch (Exception e) {
			System.out.println("Sorry ERROR");
		}
		if (IDright)
			System.out.println("Sorry the password is wrong");
		else
			System.out
					.println("Sorry the ID you input NOT found,you can input again or try to register");
		return false;
	}
}
